package org.jeecg.modules.monitoring.j_monitoring.job.history;

import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.system.entity.SysLog;
import org.jeecg.modules.system.service.ISysLogService;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;

import java.time.LocalDate;
import java.util.List;

/**
 * 同步系统日志
 * @Author: xiaoyq
 */

@Slf4j
public class SyncSysLogJob implements Job {
    @Autowired
    private ISysLogService logService;

    private SysLog getLastFromHistory(LocalDate date1){
        SysLog lastEntity = null;
        DynamicDataSourceContextHolder.push("history");
        try{
            QueryWrapper<SysLog> logHistoryQueryWrapper = new QueryWrapper();
            logHistoryQueryWrapper.lambda().lt(SysLog::getCreateTime,date1);
            logHistoryQueryWrapper.select("max(create_time) create_time");
            lastEntity = logService.getOne(logHistoryQueryWrapper);
            return lastEntity;
        }
        finally {
            DynamicDataSourceContextHolder.clear();
        }
    }

    private void saveToHistory(List<SysLog> logList){
        DynamicDataSourceContextHolder.push("history");
        try{
            logService.saveOrUpdateBatch(logList);
        }
        finally {
            DynamicDataSourceContextHolder.clear();
        }
    }

    /***
     * 执行
     * @param jobExecutionContext
     * @throws JobExecutionException
     */
    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        log.info(String.format("同步日志数据,时间:" + DateUtils.getTimestamp()));
        LocalDate date1= LocalDate.parse(DateUtils.getBeginMonth());
        date1 = date1.plusMonths(-1);//保留6个月的数据

        QueryWrapper<SysLog> logQueryWrapper = new QueryWrapper();
        SysLog lastEntity = this.getLastFromHistory(date1);
        try{
            logQueryWrapper.lambda().lt(SysLog::getCreateTime,date1);
            if(lastEntity!=null && lastEntity.getCreateTime()!=null){
                logQueryWrapper.lambda().gt(SysLog::getCreateTime,lastEntity.getCreateTime());
            }
            List<SysLog> logList = logService.list(logQueryWrapper);

            if(logList.size()>0){
                saveToHistory(logList);
                logService.remove(logQueryWrapper);
            }

        }
        finally {
            DynamicDataSourceContextHolder.clear();
        }
    }

}
